package com.sinven.controller.manage;

import com.sinven.common.UploadResult;
import com.sinven.conf.CmsProperties;
import com.sinven.util.UploadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/manage")
@Slf4j
public class UploadController {
    @Resource
    private CmsProperties cmsProps;

    @PostMapping("upload")
    public UploadResult upload(@RequestParam(value = "upload") MultipartFile file,
                               HttpServletRequest request) {
        if(file.isEmpty()){
            return UploadUtil.error("Error....Upload file is empty");
        }
        // 原文件名
        String originalFilename = file.getOriginalFilename();
        //生成存储目录
        File dest = UploadUtil.generateStorageFile(cmsProps.getUploadBaseDirectory(), originalFilename);
        //保存至服务器目录
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            return UploadUtil.error(e.getMessage());
        }
        //得到文件存储相对路径
        String relativeUrl = UploadUtil.getRelativeFileName(cmsProps.getUploadBaseFolder(),dest);
        //得到访问路径
        String requestUrl = "http://"+cmsProps.getServerPath()+"/"+relativeUrl;
        String filename = relativeUrl.substring(relativeUrl.lastIndexOf("/"));
        return UploadUtil.success(filename,requestUrl);
    }
}
